package cn.lg.soar.common.util.trans.jackson;

import cn.lg.soar.common.util.trans.handler.ITranslateHandler;
import cn.lg.soar.common.util.trans.model.TranslateContext;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.lang.annotation.Annotation;

/**
 * @author luguoxiang
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
public class TranslateDeserializer<T, A extends Annotation> extends JsonDeserializer<T> {

    protected static final Logger LOGGER = LoggerFactory.getLogger(TranslateDeserializer.class);

    private final TranslateContext<T> translateContext;
    private final ITranslateHandler<T> handler;
    private final A annotation;
    private final String fieldName;

    public TranslateDeserializer(TranslateContext<T> translateContext, Annotation annotation) {
        this.annotation = (A) annotation;
        this.translateContext = translateContext;
        this.handler = translateContext.getHandler();
        this.fieldName = translateContext.getTranslateName();
    }


    @Override
    public T deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
        return handler.convertToJava(jsonParser.getText(), annotation, translateContext);
    }

}
